<template>
  <div class="labelManage">
    <div class="topbox">
      <el-form ref="form" label-position="left" label-width="80px">
          <el-row :gutter="20">
            <el-col :span="5">
                <el-form-item label="用电企业">
                  <FilterSelect ref="jianzhuqun" 
                  :optionlist="options" 
                  :valuekey="{name:'orgName',value:'orgNo'}" 
                  @changeselect="changeqiye" 
                  :defaultvalue="orgNo"
                  ></FilterSelect>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="标签">
                  <el-input
                    v-model="labelName"
                    placeholder="输入标签"
                    size="small"
                    style="width: 100%"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="14" style="text-align: right;">
                <el-form-item label="">
                  <el-button size="small" @click="chongzhi">重 置</el-button>
                  <el-button type="primary" size="small" @click="gettablelist">查 询</el-button>
                </el-form-item>
              </el-col>
          </el-row>
      </el-form>
    </div>
    <div class="bodybox">
      <div class="titlebox">
        <div><el-button type="primary" size="small" @click="$refs.Dialogref.dialogVisible=true"><i class="el-icon-plus"></i> 新增</el-button></div>
        <div><TopTile  @command="command" @daochu="daochu" @shuaxin="shuaxin"></TopTile></div>
      </div>
      <div class="table">
        <TableColumn
          ref="tabledata"
          :tableData="tableData" 
          :tableConfig="tableConfig" 
          :issize="issize">
          <el-table-column
              prop="address"
              label="操作"
              align="center"
              width="200">
              <template #default="{row}">
                <el-button type="text" @click="addlabel(row,true)">修改</el-button>
                <el-button type="text" @click="dellist(row)">删除</el-button>
                <el-button type="text" @click="addlabel(row)">添加标签</el-button>
              </template>
          </el-table-column>
        </TableColumn>
        <Dialog :options="options" @togetlist="gettablelist" ref="Dialogref"></Dialog>
        <el-dialog
          :title="isflag?'修改标签':'新增标签'"
          :visible.sync="dialogVisible"
          @close="quxiao"
          width="30%">
          <div>
            <el-form ref="form" :model="form" label-width="80px">
                <el-row >
                    <el-col :span="15">
                      <el-form-item label="设备名称">
                        <el-input v-model="form.deviceName" placeholder="" size="small"></el-input>
                      </el-form-item>
                    </el-col>
                </el-row>
                <el-row v-for="(item,index) in labellist" :key="index">
                    <el-col :span="15">
                      <el-form-item label="标签">
                        <el-select v-model="item.tagId" placeholder="选择标签" size="small" @change="changetag(index)" clearable filterable style="width:100%;">
                            <el-option v-for="(item,index) in labeloption" :key="index" :label="item.labelName" :value="item.tagId">
                            </el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="9" style="padding-top: 5px;padding-left: 20px;">
                      <el-button type="danger" size="small" @click="del(index)">删除</el-button>
                    </el-col>
                </el-row>
                <el-row >
                  <el-col :span="15">
                    <el-form-item label="">
                      <el-button type="primary" @click="labellist.push({labelName:'',tagId:''})" size="small">
                        <i class="el-icon-plus"></i> 添加标签</el-button>
                    </el-form-item>
                  </el-col>
                </el-row>
            </el-form>
          </div>
          <span slot="footer" class="dialog-footer">
            <el-button type="primary" @click="baocun" size="small">保 存</el-button>
            <el-button @click="quxiao" size="small">取 消</el-button>
          </span>
        </el-dialog>
      </div>
      <!-- 底部分页 -->
      <div class="fenye">
        <el-pagination
          background
          layout="prev, pager, next"
          :current-page.sync="pages.pageNo"
          :page-size="15"
          @current-change="gettablelist"
          :total="+totalCount"
        >
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import FilterSelect from '@/components/FilterSelect'
import {getdevicelistapi,getlabelnameapi,addlabelxinapi,deldevicelabelapi,updatedeviceapi} from '@/api/system/deviceLabel'
import {getleftlistapi} from '@/api/iot'
import Dialog from './addlabel.vue'
import TopTile from '@/components/TopTitle/index.vue'
import TableColumn from '@/components/Table/index.vue'
import {exportexcel} from '@/utils/excel'
export default {
  name: 'CallPoliceIndex',
  components: {
    Dialog,
    TopTile,
    TableColumn,
    FilterSelect
  },
  data() {
    return {
      orgNo:'',
      issize: 'medium',
      labelName: '',
      form:{},
      options: [],
      totalCount:'',
      dialogVisible:false,
      tableData: [],
      tableConfig: [
        { label: '序号', type:'index' ,center:'center',width:'100'},
        { label: '设备ID', prop: 'deviceId' },
        { label: '设备名称', prop: 'deviceName' },
        { label: '业务类型', prop: 'businessType' },
        { label: '所属企业', prop: 'companyName' },
        {
          label: '标签', prop: 'tagList',
          formatter: (row, column, cellValue, index) => {
            return cellValue?.map(ele=>ele.labelName).join(',')
          }
        },
        { label: '维护日期', prop: 'maintainDate' ,center:'center'},
      ],
      labellist: [{labelName:'',labelId:''}],
      labeloption: [],
      isflag:false,
      pages: {
        pageNo: 1,
        pageSize:15
      },
    };
  },

  async mounted() {
    const { data: { list } } = await getleftlistapi()
    this.options = list
    this.orgNo=list[0].orgNo
    this.gettablelist()
  },

  methods: {
    changeqiye(val) {
      this.$set(this,'orgNo',val)
    },
    // 获取表格数据
    async gettablelist() {
      this.$refs.tabledata.loading=true
      const {data:{list,totalCount}}=await getdevicelistapi({pageNo: this.pages.pageNo - 1, pageSize: this.pages.pageSize, orgNo: this.orgNo, labelName: this.labelName})
      this.tableData = list
      this.totalCount=totalCount
      this.$refs.tabledata.loading=false
    },
    // 添加标签
    async addlabel(row, flag) {
      this.isflag=flag
      this.form={...row}
      this.dialogVisible = true
      await this.getlabellist(row)
      if (flag) {
        row.tagList.forEach(ele => {
          this.labeloption.push(ele)
          this.labellist=this.labellist.filter(item=>item.tagId)
          this.labellist.push({...ele})
        })
      }
    },
    changetag(currentIndex) {
      const currentValue = this.labellist[currentIndex].tagId;
      // 遍历 labellist 检查当前值是否已经被其他下拉框选中
      for (let i = 0; i < this.labellist.length; i++) {
        if (i !== currentIndex && this.labellist[i].tagId === currentValue) {
          // 如果已经被选中，给出提示并重置当前下拉框的值
          this.$message.warning('请勿重复选择标签!请重新选择');
          // 重置当前下拉框的值
          this.labellist[currentIndex].tagId = null;
          return;
        }
      }
    },
    // 获取标签名称列表
    async getlabellist(item) {
      const businessType=item.businessType=='配电管理'?'01':item.businessType=='能耗管理'?'02':item.businessType=='光伏管理'?'03':item.businessType=='微电网管理'?'04':'05'
      const { data: { list } } = await getlabelnameapi({businessType,orgNo:item.companyId,labelStatus:'',deviceId:item.deviceId})
      this.labeloption=list
    },
    del(ind) {
      if(this.labellist.length==1) return this.$message.warning('请至少选择一项标签')
      this.labellist=this.labellist.filter((item,index)=>index!==ind)
    },
    // 保存
    async baocun() {
      const businessType=this.form.businessType=='配电管理'?'01':this.form.businessType=='能耗管理'?'02':this.form.businessType=='光伏管理'?'03':this.form.businessType=='微电网管理'?'04':'05'
      const labelIdList = this.labellist.map(ele => {
        return {
          tagId: ele.tagId,
          labelName:this.labeloption.find(item=>item.tagId==ele.tagId).labelName
        }
      })
      this.isflag?await updatedeviceapi({className:this.form.className, businessType, deviceId: this.form.deviceId, orgNo: this.form.companyId, labelIdList }).then(res => {
        this.messages(res,'修改')
      }): await addlabelxinapi({ className:this.form.className,businessType, deviceId: this.form.deviceId, orgNo: this.form.companyId, labelIdList }).then(res => {
        this.messages(res,'新增')
      })
    },
    // 提示
    messages(res, name) {
      this.$message({
        type: res.code == '200' ? 'success' : 'warning',
        message: res.code == '200' ? `${name}成功` : res.message
      })
      if (res.code == '200') this.quxiao()
      if (res.code == '200') this.gettablelist()
    },
    // 删除
    async dellist(row) {
      this.$confirm('此操作将删除该设备标签, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const res = await deldevicelabelapi({ businessType:row.businessType,deviceId:row.deviceId,orgNo:row.orgNo})
          this.$message({type: res.code == 200 ? 'success' : 'warning',message: res.code == 200 ? '删除成功':res.message})
          this.gettablelist() 
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 取消
    quxiao() {
      this.isflag=false
      this.labeloption = []
      this.form={}
      this.labellist= [{labelName:'',labelId:''}]
      this.dialogVisible = false
    },
     // 调节表格密度
    command(val) {
      if (val === '默认') {
        this.issize = 'medium'
      } else if (val === '中等') {
        this.issize = 'small'
      } else {
        this.issize = 'mini'
      }
    },
    // 导出
    daochu() {
      exportexcel('/sst-microservice-biz/sst/device/tags/export',{orgNo: this.orgNo, labelName: this.labelName},'设备标签')
    },
    // 刷新列表
    shuaxin() {
      this.gettablelist()
      this.$message.success('列表刷新成功')
    },
    chongzhi() {
      this.orgNo = this.options[0].orgNo
      this.labelName = ''
      this.gettablelist()
    },
  },
};
</script>
<style lang="scss" scoped>
.labelManage{
  padding:10px;
  height:100%;
  background-color:#f1f1f1;
  .topbox{
    height:80px;
    padding: 20px;
    justify-content: space-between;
    background-color:#fff;
    margin-bottom:10px;
  }
  .bodybox{
    padding:20px;
    height:calc(100% - 90px);
    background-color:#fff;
    .titlebox{
      display:flex;
      justify-content: space-between;
      margin-bottom:10px;
    }
    .table{
      height: 90%;
    }
    .fenye{
      margin-top: 10px;
      text-align: right;
    }
  }
}
::v-deep .el-dialog__footer{
  text-align: center;
}
</style>